
 /**
 * 上海中赢金融信息服务有限公司
 * Copyright (c) 2017, chinazyjr All Rights Reserved.
 */
package com.sys.kafka.core.partition;

import java.util.List;
import java.util.Map;

import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.PartitionInfo;

import com.sys.midware.logger.Logger;
import com.sys.midware.logger.LoggerFactory;

/**
 * <b>Description：</b> TODO <br/>
 * <b>ClassName：</b> MyPartition <br/>
 * <b>@author：</b> mobing <br/>
 * <b>@date：</b> 2017年7月12日 下午6:46:20 <br/>
 * <b>@version: </b>  <br/>
 */
public class MyPartition implements Partitioner{
    private static Logger LOG = LoggerFactory.getLogger(MyPartition.class);
    public MyPartition() {
    }

    @Override
    public void configure(Map<String, ?> configs) {

    }

    @Override
    public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
        List<PartitionInfo> partitions = cluster.partitionsForTopic(topic);
        int numPartitions = partitions.size();
        int partitionNum = 0;
        try {
            partitionNum = Integer.parseInt((String) key);
        } catch (Exception e) {
            partitionNum = key.hashCode() ;
        }
        LOG.info("the message sendTo topic:"+ topic+" and the partitionNum:"+ partitionNum);
        return Math.abs(partitionNum  % numPartitions);
    }

    @Override
    public void close() {

    }
}
